/*********************************************************************
 * KeyedObjectPoolSample.java created on Feb 2, 2010
 *
 * This file is part of Sure Tech Support Portal System. 
 * Copyright @ 2010 Sure Tech (HK) Limited. All rights reserved.
 * Sure Tech PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *********************************************************************/
package com.bizdigger.db;

import org.apache.commons.pool.BaseKeyedPoolableObjectFactory;
import org.apache.commons.pool.KeyedObjectPool;
import org.apache.commons.pool.KeyedObjectPoolFactory;
import org.apache.commons.pool.KeyedPoolableObjectFactory;
import org.apache.commons.pool.impl.StackKeyedObjectPoolFactory;

/**
 * @Author: Mac Wang
 * @Date: Feb 2, 2010 2:16:51 PM 
 * @Email: mac@suretech.com.hk
 */

public class KeyedObjectPoolSample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Object obj = null;
		KeyedPoolableObjectFactory factory = new KeyedPoolableObjectFactorySample();
		KeyedObjectPoolFactory poolFactory = new StackKeyedObjectPoolFactory(factory);
		KeyedObjectPool pool = poolFactory.createPool();
		
		String key = null;
		try
		{
			for (long i = 0; i < 100 ; i++) 
			{
				key = "" + (int) (Math.random() * 10);
				System.out.println("== " + i + " ==");
				System.out.println("Key:" + key);
				obj = pool.borrowObject(key);
				System.out.println("Object:" + obj);
				pool.returnObject(key, obj);
				obj = null;
           }
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(obj != null)
					pool.returnObject(key, obj);
				pool.close();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}

}
class KeyedPoolableObjectFactorySample extends BaseKeyedPoolableObjectFactory
{
	@Override
	public Object makeObject(Object key) throws Exception {
		return "[" + key.hashCode() + "]";
	}
	
}
